document.addEventListener('DOMContentLoaded', () => {
    const board = document.getElementById('gameBoard');
    const scoreDisplay = document.querySelector('.score span');
    const bestScoreDisplay = document.querySelector('.best-score span');
    const newGameButton = document.getElementById('newGameBtn');
    
    let boardSize = 4;
    let boardValues = [];
    let score = 0;
    let bestScore = localStorage.getItem('bestScore') || 0;
    
    bestScoreDisplay.textContent = bestScore;
    
    // 初始化游戏
    function init() {
        boardValues = [];
        score = 0;
        scoreDisplay.textContent = score;
        
        // 创建空棋盘
        for (let i = 0; i < boardSize * boardSize; i++) {
            boardValues.push(0);
            const tile = document.createElement('div');
            tile.classList.add('tile');
            board.appendChild(tile);
        }
        
        // 添加两个初始方块
        addNewTile();
        addNewTile();
        
        updateBoard();
    }
    
    // 在随机位置添加新方块（2或4）
    function addNewTile() {
        const emptyTiles = boardValues.map((val, idx) => val === 0 ? idx : null).filter(val => val !== null);
        if (emptyTiles.length === 0) return;
        
        const randomIndex = emptyTiles[Math.floor(Math.random() * emptyTiles.length)];
        boardValues[randomIndex] = Math.random() < 0.9 ? 2 : 4;
    }
    
    // 更新棋盘视觉显示
    function updateBoard() {
        const tiles = document.querySelectorAll('.tile');
        
        for (let i = 0; i < boardValues.length; i++) {
            const value = boardValues[i];
            const tile = tiles[i];
            
            tile.textContent = value === 0 ? '' : value;
            
            // 移除所有方块颜色类
            for (let j = 2; j <= 2048; j *= 2) {
                tile.classList.remove(`tile-${j}`);
            }
            
            // 添加适当的颜色类
            if (value !== 0) {
                tile.classList.add(`tile-${value}`);
            }
        }
        
        checkGameOver();
    }
    
    // 处理键盘输入
    document.addEventListener('keydown', (e) => {
        if (e.key === 'ArrowUp' || e.key === 'ArrowDown' || e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
            moveTiles(e.key);
        }
        // 添加WASD键支持
        else if (e.key.toLowerCase() === 'w') {
            moveTiles('ArrowUp');
        } else if (e.key.toLowerCase() === 's') {
            moveTiles('ArrowDown');
        } else if (e.key.toLowerCase() === 'a') {
            moveTiles('ArrowLeft');
        } else if (e.key.toLowerCase() === 'd') {
            moveTiles('ArrowRight');
        }
    });
    
    // 处理移动设备上的滑动手势
    let startX = 0;
    let startY = 0;
    
    document.addEventListener('touchstart', (e) => {
        const touch = e.touches[0];
        startX = touch.clientX;
        startY = touch.clientY;
    });
    
    document.addEventListener('touchend', (e) => {
        const touch = e.changedTouches[0];
        const endX = touch.clientX;
        const endY = touch.clientY;
        
        const deltaX = endX - startX;
        const deltaY = endY - startY;
        
        if (Math.abs(deltaX) > Math.abs(deltaY)) {
            // 水平滑动
            if (deltaX > 0) {
                moveTiles('ArrowRight');
            } else {
                moveTiles('ArrowLeft');
            }
        } else {
            // 垂直滑动
            if (deltaY > 0) {
                moveTiles('ArrowDown');
            } else {
                moveTiles('ArrowUp');
            }
        }
    });
    
    // 根据指定方向移动方块
    function moveTiles(direction) {
        let moved = false;
        
        if (direction === 'ArrowUp') {
            moved = moveUp();
        } else if (direction === 'ArrowDown') {
            moved = moveDown();
        } else if (direction === 'ArrowLeft') {
            moved = moveLeft();
        } else if (direction === 'ArrowRight') {
            moved = moveRight();
        }
        
        if (moved) {
            addNewTile();
            updateBoard();
        }
    }
    
    // 向上方移动方块
    function moveUp() {
        let moved = false;
        
        for (let col = 0; col < boardSize; col++) {
            for (let row = 1; row < boardSize; row++) {
                if (boardValues[row * boardSize + col] !== 0) {
                    let currentRow = row;
                    while (currentRow > 0 && boardValues[(currentRow - 1) * boardSize + col] === 0) {
                        boardValues[(currentRow - 1) * boardSize + col] = boardValues[currentRow * boardSize + col];
                        boardValues[currentRow * boardSize + col] = 0;
                        currentRow--;
                        moved = true;
                    }
                    
                    if (currentRow > 0 && 
                        boardValues[(currentRow - 1) * boardSize + col] === boardValues[currentRow * boardSize + col]) {
                        boardValues[(currentRow - 1) * boardSize + col] *= 2;
                        boardValues[currentRow * boardSize + col] = 0;
                        score += boardValues[(currentRow - 1) * boardSize + col];
                        scoreDisplay.textContent = score;
                        if (score > bestScore) {
                            bestScore = score;
                            bestScoreDisplay.textContent = bestScore;
                            localStorage.setItem('bestScore', bestScore);
                        }
                        moved = true;
                    }
                }
            }
        }
        
        return moved;
    }
    
    // 向下方移动方块
    function moveDown() {
        let moved = false;
        
        for (let col = 0; col < boardSize; col++) {
            for (let row = boardSize - 2; row >= 0; row--) {
                if (boardValues[row * boardSize + col] !== 0) {
                    let currentRow = row;
                    while (currentRow < boardSize - 1 && boardValues[(currentRow + 1) * boardSize + col] === 0) {
                        boardValues[(currentRow + 1) * boardSize + col] = boardValues[currentRow * boardSize + col];
                        boardValues[currentRow * boardSize + col] = 0;
                        currentRow++;
                        moved = true;
                    }
                    
                    if (currentRow < boardSize - 1 && 
                        boardValues[(currentRow + 1) * boardSize + col] === boardValues[currentRow * boardSize + col]) {
                        boardValues[(currentRow + 1) * boardSize + col] *= 2;
                        boardValues[currentRow * boardSize + col] = 0;
                        score += boardValues[(currentRow + 1) * boardSize + col];
                        scoreDisplay.textContent = score;
                        if (score > bestScore) {
                            bestScore = score;
                            bestScoreDisplay.textContent = bestScore;
                            localStorage.setItem('bestScore', bestScore);
                        }
                        moved = true;
                    }
                }
            }
        }
        
        return moved;
    }
    
    // 向左移动方块
    function moveLeft() {
        let moved = false;
        
        for (let row = 0; row < boardSize; row++) {
            for (let col = 1; col < boardSize; col++) {
                if (boardValues[row * boardSize + col] !== 0) {
                    let currentCol = col;
                    while (currentCol > 0 && boardValues[row * boardSize + (currentCol - 1)] === 0) {
                        boardValues[row * boardSize + (currentCol - 1)] = boardValues[row * boardSize + currentCol];
                        boardValues[row * boardSize + currentCol] = 0;
                        currentCol--;
                        moved = true;
                    }
                    
                    if (currentCol > 0 && 
                        boardValues[row * boardSize + (currentCol - 1)] === boardValues[row * boardSize + currentCol]) {
                        boardValues[row * boardSize + (currentCol - 1)] *= 2;
                        boardValues[row * boardSize + currentCol] = 0;
                        score += boardValues[row * boardSize + (currentCol - 1)];
                        scoreDisplay.textContent = score;
                        if (score > bestScore) {
                            bestScore = score;
                            bestScoreDisplay.textContent = bestScore;
                            localStorage.setItem('bestScore', bestScore);
                        }
                        moved = true;
                    }
                }
            }
        }
        
        return moved;
    }
    
    // 向右移动方块
    function moveRight() {
        let moved = false;
        
        for (let row = 0; row < boardSize; row++) {
            for (let col = boardSize - 2; col >= 0; col--) {
                if (boardValues[row * boardSize + col] !== 0) {
                    let currentCol = col;
                    while (currentCol < boardSize - 1 && boardValues[row * boardSize + (currentCol + 1)] === 0) {
                        boardValues[row * boardSize + (currentCol + 1)] = boardValues[row * boardSize + currentCol];
                        boardValues[row * boardSize + currentCol] = 0;
                        currentCol++;
                        moved = true;
                    }
                    
                    if (currentCol < boardSize - 1 && 
                        boardValues[row * boardSize + (currentCol + 1)] === boardValues[row * boardSize + currentCol]) {
                        boardValues[row * boardSize + (currentCol + 1)] *= 2;
                        boardValues[row * boardSize + currentCol] = 0;
                        score += boardValues[row * boardSize + (currentCol + 1)];
                        scoreDisplay.textContent = score;
                        if (score > bestScore) {
                            bestScore = score;
                            bestScoreDisplay.textContent = bestScore;
                            localStorage.setItem('bestScore', bestScore);
                        }
                        moved = true;
                    }
                }
            }
        }
        
        return moved;
    }
    
    // 检查是否还有可移动作
    function hasMovesLeft() {
        // 如果有空单元格，可以进行移动
        for (let i = 0; i < boardValues.length; i++) {
            if (boardValues[i] === 0) return true;
        }
        
        // 检查是否有可合并的方块
        for (let i = 0; i < boardSize; i++) {
            for (let j = 0; j < boardSize; j++) {
                const current = boardValues[i * boardSize + j];
                
                // 检查右侧邻居
                if (j < boardSize - 1 && current === boardValues[i * boardSize + (j + 1)]) {
                    return true;
                }
                
                // 检查下方邻居
                if (i < boardSize - 1 && current === boardValues[(i + 1) * boardSize + j]) {
                    return true;
                }
            }
        }
        
        return false;
    }
    
    // 检查游戏是否结束
    function checkGameOver() {
        if (!hasMovesLeft()) {
            setTimeout(() => {
                alert('游戏结束！最终得分: ' + score);
                init();
            }, 200);
        }
    }
    
    // 点击按钮开始新游戏
    newGameButton.addEventListener('click', () => {
        init();
    });
    
    // 初始化游戏
    init();
});